package other;

public class SwapLinkList {
    /**
     * Definition for singly-linked list.
     */
    static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    static class Solution {
        public static ListNode swapPairs(ListNode head) {
            // 节点为空或1直接返回该节点
            if (head== null || head.next == null){
                return head;
            }

            // 添加虚拟头节点
            ListNode listNode = new ListNode(0, head);
            listNode.next = head;

            // 记录头节点
            ListNode prev = head.next;

            //交换node1和node2
            while (listNode.next != null && listNode.next.next != null){
                swap(listNode);
                listNode = listNode.next.next;
            }

            return prev;
        }

        // 交换节点
        public static void swap(ListNode node){
            ListNode one = node.next;
            ListNode two = one.next;
            node.next = two;
            one.next = two.next;
            two.next = one;
        }
    }

    // 测试
    public static void main(String[] args) {
        ListNode four = new ListNode(4);
        ListNode three = new ListNode(3,four);
        ListNode two = new ListNode(2, three);
        ListNode one = new ListNode(1, two);
        ListNode listNode = Solution.swapPairs(one);

        while (listNode != null){
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }
}
